package edu.aynu.controller;

import edu.aynu.entity.Cloze;
import edu.aynu.service.ClozeService;
import edu.aynu.service.EsClozeService;
import edu.aynu.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import javax.annotation.Resource;

/**
 * (Cloze)表控制层
 *
 * @author haha
 * @since 2021-05-20 14:37:13
 */
@RestController
public class ClozeController {
    /**
     * 服务对象
     */
    @Resource
    private ClozeService clozeService;

    @Autowired
    private EsClozeService esClozeService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("cloze")
    public Result selectOne(Integer id) {
        Cloze cloze = this.clozeService.queryById(id);
        if (cloze == null) {
            return Result.fail();
        }
        return Result.success().add("cloze", cloze);
    }

    /**
     * 通过实体作为筛选条件查询
     */
    @GetMapping("clozes")
    public Result queryAll(@RequestBody Cloze cloze) {
        List<Cloze> list = esClozeService.queryBySubject(cloze);
        //List<Cloze> list = this.clozeService.queryAll(cloze);
        if (list.size() == 0) {
            return Result.fail();
        }
        return Result.success().add("clozes", list);
    }

    /**
     * 新增数据
     */
    @PostMapping("cloze")
    public Result insert(@RequestBody Cloze cloze) {
        int i = this.clozeService.insert(cloze);
        if (i == 0) {
            return Result.fail();
        }
        return Result.success();
    }

    /**
     * 修改数据
     */
    @PutMapping("cloze")
    public Result update(@RequestBody Cloze cloze) {
        int i = this.clozeService.update(cloze);
        if (i == 0) {
            return Result.fail();
        }
        return Result.success();
    }

    /**
     * 通过主键删除数据
     *
     * @return 是否成功
     */
    @DeleteMapping("cloze")
    public Result deleteById(Integer id) {
        boolean b = this.clozeService.deleteById(id);
        if (b == false) {
            return Result.fail();
        }
        return Result.success();
    }
}
